<?php

namespace StudyBuddy\Controllers;

use StudyBuddy\UserVotesBlock;
use StudyBuddy\WebPage;
use StudyBuddy\User;
use StudyBuddy\Template\Urhere;
use StudyBuddy\ProfileDiv;
use StudyBuddy\UserTagsBlock;
use StudyBuddy\UserFollowedTags;
use StudyBuddy\UserQuestions;
use StudyBuddy\UserAnswers;

/**
 * Controller for the /users/$uid/$username page
 *
 */
class Userinfo extends WebPage
{

	protected $layoutID = 1;

	protected $aRequired = array('uid');

	protected $aAllowedVars = array('username', 'mode', 'sort');

	protected $oUser;

	protected $vars = array(
	'profile' => '',
	'questions' => '',
	'answers' => '',
	'votes' => '',
	'tags' => '');

	protected function main(){
		$this->getUser()
		->checkUsername()
		->makeTopTabs()
		->addProfile()
		->addQuestions()
		->addAnswers()
		->addVotes()
		->addFollowedTags()
		->makeRecentActivites()
		->makeRecentTags()
		->makeTutorListing()
		->addTags();
	}


	/**
	 * Create $this->oUser object
	 * that represents User whose profile
	 * is being viewed currently
	 *
	 * @throws \StudyBuddy\Exception if user could not be
	 * found by user id passed in request
	 *
	 * @return object $this
	 */
	protected function getUser(){
		$a = $this->oRegistry->Mongo->USERS->findOne(array('_id' => $this->oRequest['uid']));

		if(empty($a)){
			throw new \StudyBuddy\Exception('User not found');
		}

		$this->oUser = User::factory($this->oRegistry, $a);
		$this->aPageVars['title'] = $this->oUser->getDisplayName();

		return $this;
	}


	/**
	 * Check that username passed in url matches the
	 * username of user.
	 *
	 * @throws \StudyBuddy\RedirectException in case username passed
	 * in url does not match actual username for this user, in which
	 * case there will be a redirect to user with correct user name.
	 * This is basically good for SEO to prevent possibility of different urls
	 * pointing to the same page
	 *
	 * @return object $this
	 */
	protected function checkUsername(){
		$supplied = $this->oRequest->get('username', 's', '');

		if(!empty($supplied)){
			$username = $this->oUser->username;
			if(!empty($username) && (strtolower($username) !== strtolower($supplied) )){
				d('supplied username '.$supplied.' is not the same as actual username: '.$username);

				throw new \StudyBuddy\RedirectException('/users/'.$this->oRequest['uid'].'/'.$username);
			}
		}

		return $this;
	}

	protected function makeTopTabs(){
                $guest = null;
                if($this->oRegistry->Viewer->isGuest()) {
                    $guest['link_ask'] = '#'; // 13
                    $guest['link_ask_click'] = ' onclick="oSL.getQuickRegForm()"'; //14
                }
		d('cp');
		$tabs = Urhere::factory($this->oRegistry)->get('tplToptabs', 'questions', $guest);
		$this->aPageVars['topTabs'] = $tabs;

		return $this;
	}
	
	/**
	 * Add profile block
	 *
	 * @return object $this
	 */
	protected function addProfile(){
		$profile = ProfileDiv::factory($this->oRegistry)->setUser($this->oUser)->getHtml();
		$this->aPageVars['body'] = $profile;
		
		return $this;
	}


	/**
	 * Add block with user questions
	 *
	 * @return object $this
	 *
	 * @todo finish up with pagination
	 *
	 */
	protected function addQuestions(){

		/**
		 *
		 * html of parsed questions and pagination links
		 * at the bottom all wrapped inside <div class="user_tags">
		 * @var $userQuestions
		 */
		$userQuestions = UserQuestions::get($this->oRegistry, $this->oUser);

		/**
		 * UserQuestions::get() may return an empty string
		 * if this user does not have
		 * any questions in which case skip the
		 * rest of the method
		 */
		if(empty($userQuestions)){
			return $this;
		}

		$cond = $this->oRegistry->Request->get('sort', 's', 'recent');
		$tabs = Urhere::factory($this->oRegistry)->get('tplSortuq', $cond, array('uid' => $this->oUser->getUid()));

		$questiondBlock = '<div id="uquestions" class="sortable paginated">'.$userQuestions.'</div>';

		$this->aPageVars['body'] .= $tabs.$questiondBlock;

		return $this;
	}


	/**
	 * Add block with user's answers
	 *
	 * @return object $this
	 *
	 * @todo finish up with pagination
	 *
	 */
	protected function addAnswers(){

		/**
		 *
		 * html of parsed answers and pagination links
		 * at the bottom all wrapped inside <div class="user_answers">
		 * @var $userQuestions
		 */
		$userQuestions = UserAnswers::get($this->oRegistry, $this->oUser);

		/**
		 * UserQuestions::get() may return an empty string
		 * if this user does not have
		 * any answers in which case skip the
		 * rest of the method
		 */
		if(empty($userQuestions)){
			return $this;
		}

		$cond = $this->oRegistry->Request->get('sort', 's', 'recent');
		$tabs = Urhere::factory($this->oRegistry)->get('tplSortuans', $cond, array('uid' => $this->oUser->getUid()));

		$ansBlock = '<div id="useranswers" class="cp fl sortable paginated">'.$userQuestions.'</div>';

		$this->aPageVars['body'] .= $tabs.$ansBlock;

		return $this;
	}


	/**
	 * Add block with user votes stats
	 *
	 * @return object $this
	 */
	protected function addVotes(){
		$this->aPageVars['body'] .= UserVotesBlock::get($this->oRegistry, $this->oUser);

		return $this;
	}


	/**
	 * Add block with user's tags
	 *
	 * @return object $this
	 */
	protected function addTags(){

		$this->aPageVars['body'] .= UserTagsBlock::get($this->oRegistry, $this->oUser);

		return $this;
	}


	/**
	 * Add block that shows tags that this user
	 * is following and also possibly block with tags
	 * that both Viewer and User are following
	 *
	 * @return object $this
	 */
	protected function addFollowedTags(){

		$this->aPageVars['body'] .= UserFollowedTags::get($this->oRegistry, $this->oUser);


		return $this;
	}
	
	protected function makeRecentTags() {

        $aUserTags = $this->oRegistry->Viewer['a_f_t'];
        if (!empty($aUserTags)) {
            $s = $this->getSortedRecentTags($aUserTags);
        } else {
            $s = $this->oRegistry->Cache->get('qrecent');
        }

        $tags = \tplBoxrecent::parse(array('tags' => $s, 'title' => $this->_('Recent Tags')));
        d('cp');
        $this->aPageVars['tags'] = $tags;

        return $this;
    }

    //hoangto tutor listing
    protected function makeTutorListing() {

        $s = $this->getSortedTutors();
        $tutors = \tplTutorBox::parse(array('tutors' => $s, 'title' => $this->_('Tutor Listing')));
        d('cp');
        $this->aPageVars['tutors'] = $tutors;

        return $this;
    }

    //hoangto tutor listing
    protected function makeRecentActivites() {

        $s = $this->getSortedActivities();
        $tutors = \tplActivityBox::parse(array('ractivites' => $s, 'title' => $this->_('Recent activities')));
        d('cp');
        $this->aPageVars['activities'] = $tutors;

        return $this;
    }
    
    protected function getSortedRecentTags(array $aUserTags, $type = 'recent') {

        $limit = 9;
        if ('unanswered' === $type) {
            //$cur = $this->oRegistry->Mongo->UNANSWERED_TAGS->find(array(), array('tag', 'i_count'))->sort(array('i_ts' => -1))->limit($limit);
            $cur = $this->oRegistry->Mongo->UNANSWERED_TAGS->find(array(), array('tag', 'i_count'))->sort(array('i_count' => -1))->limit($limit);
        } else {
            //$cur = $this->oRegistry->Mongo->QUESTION_TAGS->find(array('i_count' => array('$gt' => 0)), array('tag', 'i_count'))->sort(array('i_ts' => -1))->limit($limit);
            $cur = $this->oRegistry->Mongo->QUESTION_TAGS->find(array('i_count' => array('$gt' => 0)), array('tag', 'i_count'))->sort(array('i_count' => -1))->limit($limit);
        }

        d('got ' . $cur->count(true) . ' tag results');
        $aTags = iterator_to_array($cur);

        d('aTags: ' . print_r($aTags, 1));

        if (!empty($aTags)) {
            usort($aTags, function($a, $b) use ($aUserTags) {
                        return (in_array($a['tag'], $aUserTags)) ? -1 : 1;
                    });
        };

        d('$aTags now: ' . print_r($aTags, 1));
        $html = ('unanswered' === $type) ? \tplUnanstags::loop($aTags) : \tplLinktag::loop($aTags);

        d('html recent tags: ' . $html);

        return '<div class="tag"><ul>' . $html . '</ul></div>';
    }

    //hoangto tutor listing loop
    protected function getSortedTutors() {

        $cur = $this->oRegistry->Mongo->USERS->find(array('tmp_role' => 'tutor'))->sort(array('experience' => -1))->limit(9);

        $canTeach = '';

        $func = function(&$a) use($canTeach) {
                    $a['canTeach'] = $canTeach;
                };

        $tutors = \tplTutorListing::loop($cur, true, $func);

        return $tutors;
    }

    //hoangto tutor listing loop
    protected function getSortedActivities() {

        $act_link = '';
        $badges = '';

        $func = function(&$a) use($act_link, $badges) {
                    $a['act_link'] = $act_link;
                    $a['badges'] = $badges;
                };

        $cur = $this->oRegistry->Mongo->ACTIVITIES->find()->sort(array('i_ts' => -1))->limit(5);

        $tutors = \tplActivityList::loop($cur, true, $func);

        return $tutors;
    }

}
